package com.example.educationai.controller;

import com.example.educationai.entity.User;
import com.example.educationai.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

@Slf4j
@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping("/login")
    public String showLoginForm() {
        return "simple-login";
    }

    @GetMapping("/register")
    public String showRegisterForm() {
        return "register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                          @RequestParam String email,
                          @RequestParam String password,
                          @RequestParam String confirmPassword,
                          @RequestParam String captcha,
                          HttpSession session,
                          RedirectAttributes redirectAttributes) {
        try {
            log.debug("开始处理注册请求 - 用户名: {}", username);
            
            // 验证验证码
            String sessionCaptcha = (String) session.getAttribute("captchaCode");
            if (sessionCaptcha == null || !sessionCaptcha.equalsIgnoreCase(captcha)) {
                log.debug("验证码验证失败 - 输入: {}, 会话中: {}", captcha, sessionCaptcha);
                redirectAttributes.addFlashAttribute("error", "验证码错误");
                return "redirect:/register";
            }

            // 验证密码
            if (!password.equals(confirmPassword)) {
                log.debug("密码不匹配");
                redirectAttributes.addFlashAttribute("error", "两次输入的密码不一致");
                return "redirect:/register";
            }

            // 检查用户名是否已存在
            if (userService.existsByUsername(username)) {
                log.debug("用户名已存在: {}", username);
                redirectAttributes.addFlashAttribute("error", "用户名已存在");
                return "redirect:/register";
            }

            // 检查邮箱是否已存在
            if (userService.existsByEmail(email)) {
                log.debug("邮箱已存在: {}", email);
                redirectAttributes.addFlashAttribute("error", "邮箱已被注册");
                return "redirect:/register";
            }

            // 创建新用户
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPassword(password);
            
            // 注册用户
            userService.register(user);
            log.debug("用户注册成功: {}", username);

            // 清除验证码
            session.removeAttribute("captchaCode");
            
            // 设置成功消息
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/login";
            
        } catch (Exception e) {
            log.error("注册过程中发生错误", e);
            redirectAttributes.addFlashAttribute("error", "注册失败：" + e.getMessage());
            return "redirect:/register";
        }
    }

    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws Exception {
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        String capText = defaultKaptcha.createText();
        session.setAttribute("captchaCode", capText);
        BufferedImage bi = defaultKaptcha.createImage(capText);
        ImageIO.write(bi, "jpg", response.getOutputStream());
    }

    @ExceptionHandler(Exception.class)
    public String handleError(Exception e, RedirectAttributes redirectAttributes) {
        log.error("发生错误", e);
        redirectAttributes.addFlashAttribute("error", e.getMessage());
        return "redirect:/error";
    }
} 